package com.zsix.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zsix.common.common.page.BaseController;
import com.zsix.common.common.page.PageDataTable;
import com.zsix.common.dto.controllerParams.*;
import com.zsix.common.entity.taskAssignee.*;
import com.zsix.common.util.ResultRes;
import com.zsix.common.util.StringUtils;
import com.zsix.framework.aspectj.annotation.OperLog;
import com.zsix.framework.aspectj.operate.LogConst;
import com.zsix.system.service.IApprovalTrackService;
import com.zsix.system.service.IProcessTaskService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/task")
public class ProcessTaskController extends BaseController {
    @Autowired
    private IProcessTaskService processTaskService;
    @Autowired
    private IApprovalTrackService approvalTrackService;

    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取任务表单内容")
    @PostMapping("/getHisFormJson")
    public ResultRes getHisFormJson(@RequestBody GenerWork generWork){
        try{
            return ResultRes.success(processTaskService.getHisFormJson(generWork));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "启动流程")
    @PostMapping("/startProcess")
    public ResultRes startProcess(@RequestBody ProcessTaskParams processTaskParams){
        try{
            return ResultRes.success(processTaskService.startProcess(processTaskParams));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "发送流转")
    @PostMapping("/sendWork")
    public ResultRes sendWork(@RequestBody ProcessTaskParams processTaskParams){
        HashMap<String,Object> variables=processTaskParams.getVariables();
        variables.put("isPass", "0");
        processTaskParams.setVariables(variables);
        try{
            return ResultRes.success(processTaskService.sendWork(processTaskParams));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "驳回")
    @PostMapping("/returnWork")
    public ResultRes returnWork(@RequestBody ReturnWorkEntity returnWorkEntity){
        OvTaskEntity ovTaskEntity=processTaskService.returnWork(returnWorkEntity);
        if(ovTaskEntity==null){
            return ResultRes.error("退回失败");
        }
        else{
            return ResultRes.success(ovTaskEntity);
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "移交")
    @PostMapping("/transfer")
    public ResultRes transfer(@RequestBody TaskManageParams params){
        OvTaskEntity ovTaskEntity=processTaskService.transfer(params);
        if(ovTaskEntity==null){
            return ResultRes.error("移交失败");
        }
        else{
            return ResultRes.success(ovTaskEntity);
        }
    }

    /**
     * 批量移交
     * @param param
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "批量移交")
    @PostMapping("/transferBatch")
    public ResultRes transferBatch(@RequestBody TaskManageParams param){
        try{
            return ResultRes.success(processTaskService.transferBatch(param));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "加签")
    @PostMapping("/countersign")
    public ResultRes countersign(@RequestBody TaskManageParams params){
        OvTaskEntity ovTaskEntity=processTaskService.countersign(params);
        if(ovTaskEntity==null){
            return ResultRes.error("加签失败");
        }
        else{
            return ResultRes.success(ovTaskEntity);
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "拒绝")
    @PostMapping("/refuse")
    public ResultRes refuse(@RequestBody TaskManageParams params){
        try {
            processTaskService.refuse(params);
            return ResultRes.success("申请已拒绝");
        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }

    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "手动结束流程")
    @PostMapping("/setEndTask")
    public ResultRes setEndTask(@RequestBody TaskManageParams params){
        try {
            processTaskService.setEndTask(params);
            return ResultRes.success("流程已经结束");

        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 批量结束
     * @param param
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "批量结束流程")
    @PostMapping("/setEndTaskBatch")
    public ResultRes setEndTaskBatch(@RequestBody TaskManageParams param){
        try {
            return ResultRes.success(processTaskService.setEndTaskBatch(param));

        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 删除流程
     * @param params
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.DELETE , operDesc = "删除流程实例与任务")
    @PostMapping("/deleteProcInst")
    public ResultRes deleteProcInst(@RequestBody TaskManageParams params){
        try {
            processTaskService.deleteProcInst(params);
            return ResultRes.success("流程已经删除");

        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取流程轨迹")
    @PostMapping("/getUserTaskTrack")
    public ResultRes getUserTaskTrack(@RequestBody ApprovalTrack approvalTrack){
        try{
            return ResultRes.success(approvalTrackService.getUserTaskTrack(approvalTrack));
        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 获取下一步节点信息
     * @param params
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取下一步节点信息")
    @PostMapping("/getNextNodeInfo")
    public ResultRes getNextNodeInfo(@RequestBody TaskManageParams params){
        try{
            return ResultRes.success(processTaskService.getNextTaskInfo(params));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 获取下一步接收人信息
     * @param params
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取下一步接收人信息")
    @PostMapping("/getNextUserInfo")
    public ResultRes getNextUserInfo(@RequestBody TaskManageParams params){
        try{
            return ResultRes.success(processTaskService.getNextUserInfo(params));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 获取手动选择接收人列表
     * @param selectNextUser
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取手动选择人接收列表")
    @PostMapping("/getSelectNextUsers")
    public ResultRes getSelectNextUsers(@RequestBody SelectNextUser selectNextUser){
        try {
            return ResultRes.success(processTaskService.getSelectNextUsers(selectNextUser));
        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }

    /**
     * 设置下一步接收人（手动选择有效）
     * @param manuallySelectEntityList
     * @return
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "设置下一步任务处理人")
    @PostMapping("/setNextToUsers")
    public ResultRes setNextToUsers(@RequestBody List<ManuallySelectEntity> manuallySelectEntityList){
        try {
            return ResultRes.success(processTaskService.setNextToUsers(manuallySelectEntityList));
        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }
    /**
     * 获取设置的抄送人员信息
     * @param ccParams
     * @return
     */
    @OperLog(operModul = "抄送设置" , operType = LogConst.OTHER , operDesc = "获取设置的抄送人员信息")
    @PostMapping("/getCCSelectData")
    public ResultRes getCCSelectData(@RequestBody CCParams ccParams){
        return ResultRes.success(processTaskService.getCCSelectData(ccParams));
    }
    /**
     * 抄送设置
     * @param ccParams
     * @return
     */
    @OperLog(operModul = "抄送设置" , operType = LogConst.OTHER , operDesc = "设置抄送")
    @PostMapping("/saveOrSendCC")
    public ResultRes saveOrSendCC(@RequestBody CCParams ccParams){
        return ResultRes.success(processTaskService.setCCData(ccParams));
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "触发等待任务")
    @PostMapping("/sendReceiceTask")
    public ResultRes sendReceiceTask(@RequestBody ReceiceTask receiceTask){
        try {
            return ResultRes.success(processTaskService.sendReceiceTask(receiceTask));
        }
        catch (Exception ex)
        {
            return ResultRes.error(ex.toString());
        }
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取待审核列表")
    @GetMapping("/getTodoList")
    public PageDataTable getTodoList(@RequestParam("flowName") String flowName){
        startPage();
        List<GenerWork> list=processTaskService.getTodoList(flowName);
        return getDataTable(list);
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取已审核列表")
    @GetMapping("/getHistoricTaskInstance")
    public PageDataTable getHistoricTaskInstance(@RequestParam("flowName") String flowName){
        startPage();
        List<GenerWork> list=processTaskService.getHistoricTaskInstance(flowName);
        return getDataTable(list);
    }
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取审核按钮")
    @GetMapping("/getElementButton")
    public ResultRes getElementButton(@RequestParam("taskid") String taskid){
        try {
            return ResultRes.success(processTaskService.getElementButton(taskid));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }

    /***
     * 获取轨迹图/流程图
     * @param httpServletResponse
     * @param processInstanceId
     * @param porcessKey
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取轨迹图")
    @GetMapping(value = "/getTrack")
    public void processImageGet(HttpServletResponse httpServletResponse,
                                @RequestParam("processInstanceId") String processInstanceId,
                                @RequestParam("porcessKey") String porcessKey) {
        try (OutputStream outputStream = httpServletResponse.getOutputStream()) {
            InputStream img = approvalTrackService.getFlowImgByProcInstId(processInstanceId,porcessKey);
            byte[] bytes = IOUtils.toByteArray(img);
            httpServletResponse.setContentType("image/svg+xml");
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 获取审核记录表
     */
    @OperLog(operModul = "流程审核" , operType = LogConst.OTHER , operDesc = "获取审核记录")
    @PostMapping(value = "/getApprovalTracks")
    public ResultRes getApprovalTracks(@RequestBody ApprovalTrack approvalTrack) {
        try {
            return ResultRes.success(approvalTrackService.approvalTracks(approvalTrack));
        }
        catch (Exception ex){
            return ResultRes.error(ex.toString());
        }
    }
}
